<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片组件 -->
    <el-card class="box-card">
      <!-- 信息提示 -->
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品详情"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab 栏 -->
      <el-form :model="addRuleForm" :rules="addrRules" ref="addRuleFormRef" label-width="150px">
        <el-tabs
          v-model="active"
          :tab-position="tabPosition"
          :before-leave="beforeTabChange"
          @tab-click="tabClickHandle"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addRuleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addRuleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addRuleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addRuleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="cateList"
                :props="cateProps"
                v-model="addRuleForm.goods_cat"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyDataList" :key="item.attr_id">
              <el-checkbox-group
                v-model="item.attr_vals"
                v-for="(item1, index) in item.attr_vals"
                :key="index"
              >
                <el-checkbox :label="item1"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyDataList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addRuleForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add" class="addBtn">添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片弹框 -->
    <el-dialog title="预览图片" :visible.sync="imgPreviewVisible" width="50%">
      <img :src="imgPath" alt="" class="imgPreview">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'goodAdd',
  data () {
    return {
      // 将 tab 栏定位在左边
      tabPosition: 'left',
      // 通过进度条和 tab 栏共用一个参数的方式，将进度条和 tab 栏绑定
      active: 0,
      // 添加商品信息
      addRuleForm: {
        // 商品名称
        goods_name: '',
        // 商品价格
        goods_price: 0,
        // 商品重量
        goods_weight: 0,
        // 商品数量
        goods_number: 0,
        // 商品分类
        goods_cat: [],
        // 图片上传的列表
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品参数
        attr: []
      },
      // 添加商品验证规则
      addrRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类列表
      cateList: [],
      // 级联选择器配置
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数数据列表
      manyDataList: [],
      // 静态属性数据列表
      onlyDataList: [],
      // 图片上传地址
      uploadURL: 'http://118.190.160.53:8888/api/private/v1/upload',
      // 上传图片的列表
      fileList: [],
      // 设置请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 是否展示预览图片弹框
      imgPreviewVisible: false,
      // 预览图片路径
      imgPath: ''
    }
  },
  created () {
    this.getCategories()
  },
  methods: {
    // 获取所有商品分类列表
    async getCategories () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.cateList = res.data
    },

    // 重新选中时触发
    handleChange () {
      if (this.addRuleForm.goods_cat.length !== 3) {
        this.addRuleForm.goods_cat = []
      }
    },

    // tab 切换时的钩子函数
    beforeTabChange (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addRuleForm.goods_cat.length !== 3) {
        this.$msg.error('请选择三级分类')
        return false
      }
    },

    // 当 tab 切换时触发
    async tabClickHandle () {
      if (this.active === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })

        this.manyDataList = res.data
      }
      if (this.active === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)

        this.onlyDataList = res.data
      }
    },

    // 预览图片
    handlePreview (file) {
      console.log(file)
      this.imgPreviewVisible = true
      this.imgPath = file.response.data.url
    },

    // 删除图片
    handleRemove (file) {
      // 获取需要删除的图片
      var picPath = file.response.data.tmp_path
      // 获取删除的图片再pics中的索引
      const index = this.addRuleForm.pics.findIndex(item => {
        return item.pic === picPath
      })
      // 删除图片
      this.addRuleForm.pics.splice(index, 1)
    },

    // 图片上传成功后执行的操作
    handleSuccess (response) {
      var picInfo = {
        pic: response.data.tmp_path
      }
      this.addRuleForm.pics.push(picInfo)
      console.log(this.addRuleForm.pics)
    },

    // 点击添加按钮，添加商品
    async add () {
      this.$refs.addRuleFormRef.validate(valid => {
        if (!valid) return this.$msg.error('请将必选项填写完整')
      })

      // 因为级联选择器使用的是 数组，但是后台接受的是 字符串
      // 那么如果使用传统方式将 数据 转换为字符串，那么级联选择器会报错
      // 使用深拷贝，就是在内存地址重新拷贝一份数据，原数据和最新拷贝出来的数据互相不影响
      // 也就是说需要将 this.addRuleForm 深度拷贝一份
      // 利用 lodash 库，lodash 提供了方法 cloneDeep
      var form = _.cloneDeep(this.addRuleForm)
      form.goods_cat = form.goods_cat.join(',')

      this.manyDataList.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.split(' ')
        }
        this.addRuleForm.attr.push(newInfo)
      })

      this.onlyDataList.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addRuleForm.attr.push(newInfo)
      })

      form.attr = this.addRuleForm.attr

      const { data: res } = await this.$http.post('goods', form)

      if (res.meta.status !== 201) return this.$msg.error('添加失败')

      this.$msg.success(res.meta.msg)
      this.$router.push('/goods')
    }
  },
  computed: {
    // 选中的三级分类 Id
    cateId () {
      if (this.addRuleForm.goods_cat.length === 3) {
        return this.addRuleForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}

.imgPreview {
  width: 100%;
}

/deep/ .ql-editor {
  min-height: 300px;
}

.addBtn {
  margin-top: 20px;
}
</style>
